package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.TimeZoneUtil;
import util.enviaEmail;
import bean.OSBean;
import conexao.Conexao;
import dao.OSDao;

public class proximaSituacaoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public proximaSituacaoServlet() {
        super();
     
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}
		
		int funcao = (Integer) request.getSession().getAttribute("idfuncao");

		try {
			
			if(funcao == 2){
				OSBean osBean = new OSBean();
				osBean.setId(Integer.parseInt(request.getParameter("id")));
				osBean.setDataAprovar(new TimeZoneUtil().getHoraLocal());
				
				new OSDao().enviaOSAprovar(conn, osBean);
				conn.commit();
			}
			if(funcao == 3){
				OSBean osBean = new OSBean();
				osBean.setId(Integer.parseInt(request.getParameter("id")));
				osBean.setDataProducao(new TimeZoneUtil().getHoraLocal());
				
				new OSDao().enviaOSProducao(conn, osBean);
				conn.commit();
			}
			if(funcao == 4){
				OSBean osBean = new OSBean();
				osBean.setId(Integer.parseInt(request.getParameter("id")));
				osBean.setDataEntrega(new TimeZoneUtil().getHoraLocal());
				
				new OSDao().enviaOSEntrega(conn, osBean);
				conn.commit();
			}
			if(funcao == 5){
				if(request.getParameter("entregue") != "" ){
					OSBean osBean = new OSBean();
					osBean.setId(Integer.parseInt(request.getParameter("id")));
					osBean.setAtivo(0);
					osBean.setDataFinalizado(new TimeZoneUtil().getHoraLocal());
					osBean.setEntregue(request.getParameter("entregue"));
					
					new OSDao().finalizarOs(conn, osBean);
					conn.commit();
				}else{
					out.print("Você tem que informar pra quem foi entregue!");
				}
			}
			

		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
				ex.printStackTrace();
			}
			new enviaEmail().enviar(e);
			throw new RuntimeException(e);
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
			}
		}
		
	}

}
